import utils from "@/libs/utils"

let imgs;
function check() {
    let index;
    for (index = 0; index < imgs.length; index += 5) {
        let el = imgs[index];
        if (isIn(el)) {
            loadImg(index);
        }
    }
}
//用来判断bound.top<=clientHeight的函数，返回一个bool值
function isIn(el) {
    let bound = el.getBoundingClientRect(),
        ViewprotSize = utils.getViewportSize(),
        clientHeight = ViewprotSize.height;
    return bound.top <= clientHeight;
}

function loadImg(index) {
    let i = index, len = i + 5;
    for (i; i < len; i++) {
        let el = imgs[i];
        let source = el.dataset.img;
        el.src = source;
    }
}

export default {
    mounted(el) {
        imgs = el.getElementsByClassName('thumb-img');
        // 懒加载
        setTimeout(() => {
            init();
        }, 300);
        function init() {
            check();
            window.onresize = () => {
                utils.debounce(check(), 50)
            }
            window.onscroll = () => {
                utils.debounce(check(), 80)
            }
        }
    },
    updated(el) {
        imgs = el.getElementsByClassName('thumb-img');
        // 懒加载
        setTimeout(() => {
            check();
        }, 300);
    }
}